package red.stu.wechat.factory.robot;

import java.io.File;
import java.util.HashMap;
import java.util.Set;
import java.util.UUID;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;

import org.springframework.stereotype.Component;

/**
 * 微信机器人工厂
 * @author yihrmc
 *
 */
@Component("weChatRobotFactory")
public class WeChatRobotFactory {
	
	private HashMap<String, WeChatRobot> robots = new HashMap<>();
	private final Handler defaultLogLevel;
	
	public WeChatRobotFactory() {
		this(0);
	}
	
	public WeChatRobotFactory(int level) {
		defaultLogLevel = new ConsoleHandler();
		Level l;
		switch (level) {
			default:
			case 0:
				l = Level.OFF;
				break;
			case 1:
				l = Level.SEVERE;
				break;
			case 2:
				l = Level.WARNING;
				break;
			case 3:
				l = Level.INFO;
				break;
			case 4:
				l = Level.CONFIG;
				break;
			case 5:
				l = Level.FINE;
				break;
			case 6:
				l = Level.FINER;
				break;
			case 7:
				l = Level.FINEST;
				break;
			case 8:
				l = Level.ALL;
				break;
		}
		defaultLogLevel.setLevel(l);
	}
	
	public synchronized WeChatRobot builder(WeChatRoobotCallback callback) {
		return builder(callback, null, null);
	}
	
	public synchronized WeChatRobot builder(WeChatRoobotCallback callback, File folder, Handler handler) {
		String rid = UUID.randomUUID().toString();
		WeChatRobot robot = new WeChatRobot(rid, callback, folder, handler);
		callback.onInit(robot);
		robots.put(rid, robot);
		return robot;
	}
	
	public synchronized Set<String> getRobotRids() {
		return robots.keySet();
	}
	
	public synchronized WeChatRobot getRobot(String rid) {
		return robots.get(rid);
	}
	
	public synchronized void removeRobot(String rid) {
		robots.remove(rid);
	}
	
}
